let menuList = [
  {
    id: 0,
    name: "自动滚动",
    title: "自动滚动",
    active: false,
  },
  {
    id: 1,
    name: "标识表格",
    title: "查找页面表格（el-table和ivu-table）是否存在",
    active: false,
  },
  {
    id: 999,
    name: "test",
    title: "test",
    active: false,
  },
]

// 这里的js其实是操作popup.html产生的dom的
document.addEventListener("DOMContentLoaded", function () {
  // renderMenu(MENU_LIST)
  // sendMessageToContentScript(MENU_LIST)

  sendMessageToContentScript({ id: 110 }, res => {
    renderMenu(res)
  })
  // renderMenu([{
  //   id: 1,
  //   title: '',
  //   active: true,
  //   name: 'test'
  // }])
})

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  switch (message.type) {
    case "update:menu":
      // menuList = message.data
      renderMenu(menuList)
      break

    default:
      break
  }
  sendResponse("popup已收到最新的菜单列表")
  return
  // renderMenu(MENU_LIST)
  // sendResponse()
})
/**
 * 渲染菜单列表
 * @param {object[]} menuList 菜单列表
 */
function renderMenu(menuList) {
  let $menu = document.querySelector(".menu")
  $menu.innerHTML = ""
  menuList.forEach(item => {
    $menu.appendChild(data2MenuItem(item))
  })
}

/**
 * 将菜单项数据转为DOM节点
 * @param {object} data
 * @returns {Element}
 */
function data2MenuItem(data) {
  let item = document.createElement("div")
  item.className = "menu-item"
  item.title = data.title
  item.innerHTML = data.name
  let s = document.createElement("i")
  s.className = "switch" + (data.active ? " active" : "")
  item.appendChild(s)
  item.addEventListener("click", function (e) {
    let target = e.target
    let className = target.className
    if (target.nodeName.toLowerCase() === "i") {
      if (~className.indexOf("active")) {
        target.className = className.replace("active", "")
        data.active = false
      } else {
        target.className = className + " active"
        data.active = true
      }
      sendMessageToContentScript(data)
    }
  })
  return item
}

// 向content_scripts发送消息
function sendMessageToContentScript(message, callback) {
  chrome.tabs.query(
    {
      active: true,
      currentWindow: true,
    },
    function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
        if (response) callback(response)
      })
    }
  )
}
